package com.shadow.demo.data.bo;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shadow.demo.common.constants.PunctuationConstants;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

/**
 * 分页查询对象.
 */
@Data
@EqualsAndHashCode(callSuper = true)
public class Query<T> extends LinkedHashMap<String, Object> {

    private static final long serialVersionUID = 1L;

    /** 当前页数. **/
    private static final String PAGE_CURRENT = "page";
    /** 每页显示数. **/
    private static final String PAGE_LIMIT = "limit";
    /** 当前页码. */
    private int currPage = 1;
    /** 每页条数. */
    private int limit = 10;

    /** mybatis-plus分页参数. */
    private Page<T> page;

    /**
    * 构建查询对象（根据mybatis-plus前台的分页参数）.
    **/
    public Query(final Map<String, Object> params) {
        this.putAll(params);

        //分页参数
        if (params.get(PAGE_CURRENT) != null) {
            currPage = Integer.parseInt((String) params.get(PAGE_CURRENT));
        }
        if (params.get(PAGE_LIMIT) != null) {
            limit = Integer.parseInt((String) params.get(PAGE_LIMIT));
        }

        this.put("offset", (currPage - 1) * limit);
        this.put(PAGE_CURRENT,  currPage);
        this.put(PAGE_LIMIT, limit);
        // mybatis-plus分页
        this.page = new Page<>(currPage, limit);
        // 设置排序
        this.page.setOrders(getOrderItems(params));
    }

    /**
    * 获取字段排序.
    **/
    public List<OrderItem> getOrderItems(final Map<String, Object> params) {
        final List<OrderItem> orders = new ArrayList<>();
        Optional.ofNullable((String) params.get("desc")).filter(StringUtils::isNotBlank).ifPresent(orderStr ->
            Arrays.stream(orderStr.split(PunctuationConstants.SPLIT_COMMA)).forEach(order -> {
                final OrderItem item = new OrderItem();
                item.setColumn(order);
                item.setAsc(false);
                orders.add(item);
            })
        );
        Optional.ofNullable((String) params.get("asc")).filter(StringUtils::isNotBlank).ifPresent(orderStr ->
            Arrays.stream(orderStr.split(PunctuationConstants.SPLIT_COMMA)).forEach(order -> {
                final OrderItem item = new OrderItem();
                item.setColumn(order);
                orders.add(item);
            })
        );
        return orders;
    }
}
